import re,subprocess
import logging


import time
from datetime import datetime 


def get_guid(filepath)->str:
    ''' 获取指定文件中的 guid
    '''
    smdStr = f"svn cat \"{filepath}\""
    text = exe_svn_command(smdStr)
    match = re.search(r'guid:\s*(\w+)', text)
    if not match:
        #logging.warning(".meta 文件：%s 解析 GUID 失败", path)
        print(f'.meta 文件：{filepath} 解析 GUID 失败')
        return ''
    return match.group(1)

def exe_svn_command(command):
    try:
        p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                            shell=True)
        stdout, stderr = p.communicate()
        stdout = stdout.decode("gbk")
        stderr = stderr.decode("gbk")
        if stderr != "":
            print("stderr:\n",stderr)
            logging.warning(stderr)
        return stdout   
    except subprocess.CalledProcessError as e:
        print(f'Subprocess failed with return code {e.returncode}')
    except FileNotFoundError:
        print('Command not found')

def get_project_mates(svn_assets_url)->list:
    ''' 获取项目 mate 文件信息
        svn_assets_url: svn资源根目录(包含/Main/Assets)
    '''
    mate_list = []
    cmdStr = f"svn list -R {svn_assets_url} --non-interactive | find \".meta\" "
    metafile_list = exe_svn_command(cmdStr).splitlines()
    i=1
    start_time=time.time()
    for file in metafile_list:
        if "~/" in file:
            continue
        # 拼接得到文件的完整路径
        guid=get_guid(f"{svn_assets_url}/{file}")
        # guid=calculate_time(get_guid,f"{svn_assets_url}/{file}")
        if guid and guid!="":
            mate_list.append({"path":file,"guid":guid})
        if i>=10:
            break  
        i+=1
    print(time.time()-start_time)
    return mate_list
def calculate_time(calculate_func,parameter):
    # 记录起始时间  
    start_time = datetime.now()     
    result=calculate_func(parameter)
    # 记录结束时间  
    end_time = datetime.now()  
    # 计算时间差  
    time_difference = end_time - start_time  
   # 将时间差转换为毫秒  
    total_milliseconds = int(time_difference.total_seconds() * 1000)  
    # 提取小时、分钟、秒和毫秒  
    hours, remainder_ms = divmod(total_milliseconds, 3600 * 1000)  
    minutes, seconds_ms = divmod(remainder_ms, 60 * 1000)  
    seconds, milliseconds = divmod(seconds_ms, 1000)  
    # 格式化时间差为 hh:mm:ss.mmm  
    formatted_time_difference = f"{int(hours):02d}:{int(minutes):02d}:{int(seconds):02d}.{int(milliseconds):03d}"  
    print(f"——————————————{calculate_func.__name__}经过的时间:{formatted_time_difference}———————————————————")
    return result

if __name__ == '__main__':
    print()
    mate_list=calculate_time(get_project_mates,"svn://10.11.89.71/SvnToolTest")
    # get_project_mates("svn://10.11.89.71/SvnToolTest")
